<?php

namespace jjl\yii2\db;

use Yii;
use yii\db\ActiveRecordInterface;
use yii\db\BaseActiveRecord;
use yii\helpers\Inflector;
use jjl\yii2\db\Iterator;

class ActiveQuery extends \yii\db\ActiveQuery {

    public function all($db = null) {
        return parent::all($db);
    }

    public function one($db = null) {
        return parent::one($db);
    }

    /**
     * Finds the related records for the specified primary record.
     * This method is invoked when a relation of an ActiveRecord is being accessed in a lazy fashion.
     * @param string $name the relation name
     * @param ActiveRecordInterface|BaseActiveRecord $model the primary model
     * @return mixed the related record(s)
     * @throws InvalidArgumentException if the relation is invalid
     */
    public function findFor($name, $model) {
        $record = parent::findFor($name, $model);
//        根据先后依赖关系 TODO
//         原则：强关联从日志中补全数据
        if ($this->multiple) { // hasMany()
            // 包含数组形式的参数，如media_id 无法通过hasMany()函数进行link
            $realName = Inflector::singularize($name);
            $records = new Iterator($record);
            // 关联主键为ID
            if (array_key_exists('id', $this->link) && in_array($realName . '_id', array_values($this->link))) {
                if (($values = $model->{$realName . '_id'}) && is_array($values) && ($ids = array_diff($values, $records->id)))
                    $record = array_merge($record, (new \yii\db\Query())->from(Inflector::tableize(get_class($model)))->where(['IN', 'id', $ids])->all(Yii::$app->dbLog->db));
                // 关联主键为UUID
            } else if (array_key_exists('uuid', $this->link) && in_array($realName . '_uuid', array_values($this->link))) {
                if ($values = $model->{$realName . '_uuid'} && is_array($values) && ($ids = array_diff($values, $record->uuid)))
                    $record = array_merge($record, (new \yii\db\Query())->from(Inflector::tableize(get_class($model)))->where(['IN', 'uuid', $ids])->all(Yii::$app->dbLog->db));
            }
            return $record;
        } else { // hasOne()
            // 如何判定为强关联？ link中指定了主键
            if (!$record) {
                if (array_key_exists('id', $this->link)) {
                    if (($dbLog = Yii::$app->dbLog->mapping($this->modelClass)->findOne($model->{$this->link['id']}))) {
                        return call_user_func(array($this->modelClass, 'build'), $dbLog->object, true);
                    }
                }
                if (array_key_exists('uuid', $this->link)) {
                    if (($dbLog = Yii::$app->dbLog->mapping($this->modelClass)->findOne($model->{$this->link['uuid']}))) {
                        return call_user_func(array($this->modelClass, 'build'), $dbLog->object, true);
                    }
                }
            }
            return $record;
        }
    }

}
